#!/usr/bin/python3
# -*- coding: utf-8 -*-
from tankdb import *
from tankeasy import *
import uuid
import time
import pathlib 
import os 
# type Matter struct {
#	Uuid       string    `json:"uuid" gorm:"type:char(36);primary_key;unique"`
#	Sort       int64     `json:"sort" gorm:"type:bigint(20) not null"`
#	UpdateTime time.Time `json:"updateTime" gorm:"type:timestamp not null;default:CURRENT_TIMESTAMP"`
#	CreateTime time.Time `json:"createTime" gorm:"type:timestamp not null;default:'2018-01-01 00:00:00'"`
#	Puuid      string    `json:"puuid" gorm:"type:char(36);index:idx_matter_puuid"` //index should unique globally.
#	UserUuid   string    `json:"userUuid" gorm:"type:char(36);index:idx_matter_uu"`
#	Username   string    `json:"username" gorm:"type:varchar(45) not null"`
#	Dir        bool      `json:"dir" gorm:"type:tinyint(1) not null;default:0"`
#	Name       string    `json:"name" gorm:"type:varchar(255) not null"`
#	Md5        string    `json:"md5" gorm:"type:varchar(45)"`
#	Size       int64     `json:"size" gorm:"type:bigint(20) not null;default:0"`
#	Privacy    bool      `json:"privacy" gorm:"type:tinyint(1) not null;default:0"`
#	Path       string    `json:"path" gorm:"type:varchar(1024)"`
#	Times      int64     `json:"times" gorm:"type:bigint(20) not null;default:0"`
#	Parent     *Matter   `json:"parent" gorm:"-"`
#	Children   []*Matter `json:"-" gorm:"-"`
#	Prop       string    `json:"prop" gorm:"type:varchar(1024) not null;default:'{}'"`
#	VisitTime  time.Time `json:"visitTime" gorm:"type:timestamp not null;default:'2018-01-01 00:00:00'"`
#	Deleted    bool      `json:"deleted" gorm:"type:tinyint(1) not null;index:idx_matter_del;default:0"`
#	DeleteTime time.Time `json:"deleteTime" gorm:"type:timestamp not null;index:idx_matter_delt;default:'2018-01-01 00:00:00'"`
#}

# vim /etc/sysctl.conf 
# 注意添加的内容：
# fs.inotify.max_user_watches=99999999（你想设置的值）

class Tank():
    def __init__(self, homepath, db_name, db_host, db_user_name, db_user_pwd, db_port, db_charset) -> None:
        self.homepath = homepath
        self.db_name = db_name
        self.db_host = db_host
        self.db_user_name = db_user_name
        self.db_user_pwd = db_user_pwd
        self.db_port = db_port
        self.db_charset = db_charset
        self.db = TankDb(db_name, db_host, db_user_name, db_user_pwd, db_port, db_charset)
        return

    def pretreatment(self, path, name, pathname):
        print("pretreatment", path, name, pathname)
        user_name, dbpath, fpath, ret = split_user(self.homepath, pathname, path, name)
        if not ret:
            return False ,0,0,0,0,0
        user_uuid = self.db.search_user_uuid(user_name)
        if user_uuid is None:
            return False ,0,0,0,0,0
        if fpath == "root":
            puuid = "root"
        else:
            puuid = self.db.search_uuid(fpath)
            print("fpath: {} puuid: {}".format(fpath, puuid))
            if puuid is None:
                return False,0,0,0,0,0
        return True, puuid, user_uuid, user_name, dbpath, uuid.uuid4()


    # ok create
    def create(self, dir, path, name, pathname):
        name = name
        ret , puuid, user_uuid, username, dbpath, uid = self.pretreatment(path, name, pathname)
        if not ret:
            return False
        sort = int(round(time.time() * 1000))
        isdir = 0
        size = 4096
        if dir:
            isdir = 1
        else:
            f = pathlib.Path(pathname)
            if f.exists():
                size = f.stat().st_size
        ret = self.db.insert_matter(uid, user_uuid, username, puuid, isdir, name, dbpath, sort, size)
        return ret
    
    # ok delete 
    def delete(self, dir, path, name, pathname):
        print("tank delete")
        user_name, dbpath, fpath, ret = split_user(self.homepath, pathname, path, name)
        if not user_name or not dbpath:
            print("not find {}".format(pathname))
            return False
        if not ret:
            print("not find root")
            return False
        ret = self.db.delete_matter(dbpath)
        #if dir:
        #    self.db.delete_matter_dir(dbpath)
        return ret

    # ok create
    def movedto(self, dir, path, name, pathname, src_pathname=""):
        print("tank moved_to {}".format(pathname))
        name = name
        ret , puuid, user_uuid, username, dbpath, uid = self.pretreatment(path, name, pathname)
        if not ret:
            return False
        sort = int(round(time.time() * 1000))
        isdir = 0
        size = 4096
        if dir:
            isdir = 1
        else:
            f = pathlib.Path(pathname)
            if f.exists():
                size = f.stat().st_size
        self.db.insert_matter_moved_to(uid, user_uuid, username, puuid, isdir, name, dbpath, sort, size)
        if dir:
            self.movedto_dir(pathname, self.movedto)
        return 

    # ok delete
    def moved_from(self, dir, path, name, pathname):
        print("tank moved_from {}".format(pathname))
        user_name, dbpath, fpath, ret = split_user(self.homepath, pathname, path, name)
        if not user_name or not dbpath:
            print("not find {}".format(pathname))
            return False
        ret = self.db.delete_matter(dbpath)
        if dir:
            self.db.delete_matter_like(dbpath+"/")
        return ret

    def movedto_dir(self, pathname, func):
        for root,dirs,files in os.walk(pathname):
            for name in dirs:#遍历文件夹
                dirPath =os.path.join(root, name) #拼接目录路径
                print(True, root, name, dirPath)
                func(True, root, name, dirPath)   
            for name in files:#遍历文件
                dirPath =os.path.join(root, name) #拼接目录路径
                print(False, root, name, dirPath)
                func(False, root, name, dirPath)       
        return 